package com.hunter.applearn.api


import android.util.Log
import com.hunter.applearn.api.ApiConfig.Companion.BASE_URL
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.IOException
import org.json.JSONObject

object Api {
    // 单例模式
    // 让所以api配置在一个地方管理
    // 私有变量保护内部数据
    // 方便扩展
    private var requestUrl: String = ""
    private var mParams: Map<String, Any> = emptyMap()

    private var okHttpClient: OkHttpClient? = null

    fun config(url: String, params: Map<String, Any> = emptyMap()): Api {
        okHttpClient = OkHttpClient.Builder().build()
        requestUrl = BASE_URL + url
        mParams = params.toMap()
        return this
    }

    // 获取RequestUrl
    fun getRequestUrl(): String = requestUrl

    // 获取参数Params
    fun getParams(): Map<String, Any> = mParams

    fun postRequest(callBack: TtitCallBack) {
        // 模拟发送json请求体到接收处理
        // 要发送的json请求体
        val json = JSONObject(mParams)

        // 把接收到的json请求体序列化成字符串
        val requestBody = json.toString()
            .toRequestBody("application/json;charset=utf-8".toMediaType())

        // 创建请求
        val request = Request.Builder()
            .url(requestUrl)
            .post(requestBody)
            .build()

        // 发送请求 创建回调对象newcall() 发起请求enqueue()
        okHttpClient?.newCall(request)
            ?.enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // 网路请求失败
                    Log.e("onFailure", "${e.message}")
                    callBack.onFailure(e)
                }

                override fun onResponse(call: Call, response: Response) {
                    // 网络请求成功
                    val result: String? = response.body?.string()
                    Log.e("onResponse", response.message)
                    callBack.onSuccess(result)
                }

            })

    }
}